package com.sbs.gaoxinqutoilet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.reflect.TypeToken;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.base.BaseScanActivity;
import com.sbs.gaoxinqutoilet.entity.AcceptanceEntity;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by 聪明一只哈 on 2018/6/14.
 * Time: 2018/6/14  14:54
 */

public class AccepterActivity extends BaseScanActivity {

    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.accepter_rv)
    RecyclerView accepterRv;
    @BindView(R.id.bt_multies)
    Button bt_Multies;
    private Unbinder unbinder;
    private AccepterAdapter accepterAdapter;
    private String acceptance_url;
    private String token_data;
    public List<AcceptanceEntity> acceepterlist = new ArrayList<>();


    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_accepter);
        unbinder = ButterKnife.bind(this);
        toolbarBack.setVisibility(View.VISIBLE);


        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");

        Intent intent = getIntent();

        acceepterlist.clear();


        String str_flag = intent.getStringExtra(Constants.YANSHOUREN);
        String level_item = intent.getStringExtra("level_item");
        if (!TextUtils.isEmpty(str_flag)){
            switch(str_flag){
                case "检查":
                    toolbarTitle.setText("选择检查小组");
                    if("市级".equals(level_item)){
                        level_item="301";
                    }else if("县级".equals(level_item)){
                        level_item="302";
                    }
                    acceptance_url= HttpApis.checkDetial_accepter+"?jiancha_level="+level_item;
                    //showShortToast("检查小组电话的数据,正在添加调整");
                    Log.i("获得url", "initContentView: 检查:"+acceptance_url);
                    break;
                case "验收":
                    toolbarTitle.setText("选择验收人");
                   // showShortToast("验收人电话的数据,正在添加调整");
                    acceptance_url=HttpApis.acceptDetial_accepter;
                    Log.i("获得url", "initContentView: 验收:"+acceptance_url);
                    break;

                default:

                    break;
            }
        }


        initView();

        initData();


    }


    /**
     * 初始化view
     */
    @Override
    protected void initView() {



        GridLayoutManager gridLayoutManager = new GridLayoutManager(AccepterActivity.this, 2);
        accepterRv.setLayoutManager(gridLayoutManager);

    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {


    }

    /**
     * 初始化数据
     */
    private void initData() {

        showLoadingDialog("请稍等...");
        //String acceptance_url = HttpApis.acceptDetial_accepter;
        //acceptance_url = HttpApis.checkDetial_accepter;

        LogUtils.i("验收人url", "initData: " + acceptance_url);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(mActivity, acceptance_url,map, new Request() {

            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                LogUtils.i("验收人url", jsonStr);

                Type type = new TypeToken<ArrayList<AcceptanceEntity>>() {
                }.getType();

                ArrayList<AcceptanceEntity> acceptanceEntities = JsonUtil.json2Collection(jsonStr, type);

                if (acceptanceEntities != null && acceptanceEntities.size() > 0) {
                    processEntity(acceptanceEntities);
                }else {
                    bt_Multies.setVisibility(View.GONE);
                }

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                LogUtils.i("验收人url", error);
                cancelLoadingDialog();
            }
        });


    }

    /**
     * 加载解析数据
     *
     * @param acceptanceEntities
     */
    private void processEntity(ArrayList<AcceptanceEntity> acceptanceEntities) {

        accepterAdapter = new AccepterAdapter(this, acceptanceEntities);
        accepterRv.setAdapter(accepterAdapter);


    }
    @OnClick({R.id.toolbar_back, R.id.bt_multies})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                acceepterlist.clear();
                finish();
                break;
            case R.id.bt_multies:

                //String accetptedata_show = accepterAdapter.acceepterlist.toString();
                //List<AcceptanceEntity> accetptedata_show = accepterAdapter.acceepterlist;
                List<AcceptanceEntity> accetptedata_show = acceepterlist;
                LogUtils.i("验收人回传", "onViewClicked: "+accetptedata_show);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                //bundle.putString("bundle", accetptedata_show);
                //bundle.putCharSequenceArrayList("bundle", accetptedata_show);
                bundle.putSerializable("bundle", (Serializable)accetptedata_show);
                intent.putExtra("inters", bundle);
                setResult(RESULT_OK, intent);


                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {

        if(acceepterlist!=null&&acceepterlist.size()>0){
            acceepterlist.clear();
        }

        super.onBackPressed();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unbinder.unbind();
        OkHttpUtils.getInstance().cancelTag(this);
    }



    public class AccepterAdapter extends RecyclerView.Adapter<AccepterAdapter.AccepterViewHolder> {


        private Context context;
        private ArrayList<AcceptanceEntity> list;
        private LayoutInflater inflater;


        private String text_content;


        public AccepterAdapter(Context context, ArrayList<AcceptanceEntity> list) {

            this.context = context;
            this.list = list;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public AccepterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = inflater.inflate(R.layout.item_accepter, parent, false);

            return new AccepterViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final AccepterViewHolder holder, final int position) {

            holder.name_tv.setText(list.get(position).getText());

            if (position % 2 == 0) {
                holder.image_a.setBackgroundResource(R.drawable.man);
            } else {
                holder.image_a.setBackgroundResource(R.drawable.woman);
            }
            holder.setData(position);

        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }

        class AccepterViewHolder extends RecyclerView.ViewHolder {

            CheckBox checkBoxAccepter;
            TextView name_tv;
            ImageView image_a, ima_selected;
            boolean isSelected=false;

            public AccepterViewHolder(View itemView) {
                super(itemView);

                name_tv = (TextView) itemView.findViewById(R.id.tv_accept);
                image_a = (ImageView) itemView.findViewById(R.id.image_accepter);
                ima_selected = (ImageView) itemView.findViewById(R.id.image_selected);
                checkBoxAccepter = (CheckBox) itemView.findViewById(R.id.check_box_accepter);


            }



            public void setData(final int position) {


                //先清空,再添加
                //acceepterlist.clear();

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                    if (stellistener!=null){
//                        stellistener.show(list.get(position).getText());
//                    }
                        if (!isSelected) {
                            ima_selected.setBackground(ContextCompat.getDrawable(context, R.drawable.rb_yes));
                            acceepterlist.add(list.get(position));
                        } else {
                            ima_selected.setBackground(ContextCompat.getDrawable(context, R.drawable.rb_no));
                            if (acceepterlist.contains(list.get(position))) {
                                acceepterlist.remove(list.get(position));
                            }
                        }
                        isSelected=!isSelected;
                        Log.i("状态值", "onClick: "+isSelected);




                    }
                });

            }
        }
    }

}
